//
//  SLEditPWDViewController.m
//  SecondLoan
//
//  Created by Echo Zhangjie on 2019/8/29.
//  Copyright © 2019 姚永波. All rights reserved.
//

#import "SLEditPWDViewController.h"
#import "SLEditPWDTableViewCell.h"
#import "SLCodeInputView.h"
#import "UIView+JXNIB.h"
#import "NSString+Tools.h"

@interface SLEditPWDViewController ()<UITableViewDelegate, UITableViewDataSource, SLCodeInputViewDelegate, UITextFieldDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *rowDataArray;
@property (nonatomic, strong) NSMutableArray *rowHintArray;
@property (nonatomic, strong) UIButton *saveBtn;
@property (nonatomic, assign) CGFloat lastSendcodeTime;
@property (nonatomic, strong) NSString *oldPWD;
@property (nonatomic, strong) NSString *nowPWD;
@property (nonatomic, strong) NSString *nowRepeatPWD;

@property (strong, nonatomic) SLCodeInputView *codeTimerView;

@end

@implementation SLEditPWDViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"密码管理";
    self.view.backgroundColor = UIColor.whiteColor;
    [self setupTableView];
    [self setupSaveBtn];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}

- (void)setupTableView {
    self.tableView = [[UITableView alloc] initWithFrame: CGRectMake(0, KStatusBarAndNavigationBarHeight, SCREEN_WIDTH, SCREEN_HEIGHT - KStatusBarAndNavigationBarHeight) style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    [self.tableView registerNib:[UINib nibWithNibName:@"SLEditPWDTableViewCell" bundle:nil] forCellReuseIdentifier:@"SLEditPWDTableViewCell"];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.scrollEnabled = NO;
    self.tableView.tableFooterView = [[UIView alloc] init];
    self.rowDataArray = [NSMutableArray arrayWithObjects:@"旧密码", @"新密码", @"确认新密码", nil];
    self.rowHintArray = [NSMutableArray arrayWithObjects:@"请输入旧密码", @"8-16位数字字母组合密码",@"8-16位数字字母组合密码", nil];
}

- (void)setupSaveBtn {
    self.view.fsBackGroundColor(0xffffff).develop(^(FFactory * factory){
        factory.button().fsBackGroundImage(@"btn_bg").fsFontSize(20.0).fsText(@"保存").fsTextColor(0xffffff).fsOnClick(save).fsClip(YES).fsRadius(3.3).fsFvid(@"saveBtn");
    });
    [fQuery(self.view, @"saveBtn") mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).with.offset(KStatusBarAndNavigationBarHeight + 180);
        make.left.equalTo(self.view).with.mas_offset(10);
        make.right.equalTo(self.view).with.mas_offset(-10);
        make.height.equalTo(@50);
    }];
}

#pragma mark ==== UITableView ======
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 54;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SLEditPWDTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SLEditPWDTableViewCell" forIndexPath:indexPath];
    [cell setTitle:self.rowDataArray[indexPath.row]];
    cell.pwdTextField.secureTextEntry = YES;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.pwdTextField.placeholder = self.rowHintArray[indexPath.row];
    [cell setTextFieldDelegate:self];
    return cell;
}

- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 3;
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
  UITableViewCell *cell = (UITableViewCell *)[[textField superview] superview];
  NSIndexPath *indexPath = [_tableView indexPathForCell:cell];
  if (indexPath.row == 0) {
    self.oldPWD = textField.text;
  } else if (indexPath.row == 1) {
    self.nowPWD = textField.text;
  } else if (indexPath.row == 2) {
    self.nowRepeatPWD = textField.text;
      if (![self.nowPWD isEqualToString:self.nowRepeatPWD]) {
          [self HUDshowErrorWithStatus:@"两次新密码不相同"];
      }
  }
}

- (void)save {
    BOOL isValidPWD = NO;
    [self.tableView endEditing:YES];
    if (self.oldPWD.length == 0) {
        [self HUDshowErrorWithStatus:@"请填写旧密码"];
        return;
    }
    if (self.nowPWD.length == 0) {
        [self HUDshowErrorWithStatus:@"请填写新密码"];
        return;
    }
    if (self.nowRepeatPWD.length == 0) {
        [self HUDshowErrorWithStatus:@"请填写确认新密码"];
        return;
    }
    if (!isEmptyString(self.oldPWD) && !isEmptyString(self.nowPWD) && !isEmptyString(self.nowRepeatPWD)) {
        isValidPWD = YES;
    }
    if (isValidPWD) {
        if (self.nowPWD.length > 0) { //
            if ([self.nowPWD isEqualToString:self.oldPWD]) {
                [self HUDshowSuccessWithStatus:MsgHintNewEqualOld];
                return;
            }
            if(![self.nowPWD  judgePassWordLegal]) {
                [self HUDshowErrorWithStatus:MsgHintPasswordValid];
                return;
            }
            if (![self.nowPWD isEqualToString:self.nowRepeatPWD]) {
                [self HUDshowErrorWithStatus:@"两次新密码不相同"];
                return;
            }
        }else{
            [self HUDshowErrorWithStatus:MsgHintNewPasswordNeed];
            return;
        }
        if (self.codeTimerView == nil) {
            SLCodeInputView *view = [[UIView viewsWithNibName:@"SLCodeInputView"] firstObject];
            view.delegate = self;
            self.codeTimerView = view;
            [view updateCodeAlertViewWithTitle:@""];
        }else{
            [self.codeTimerView showShadowView:YES];
            self.codeTimerView.hidden = NO;
        }
    } else {
      [self HUDshowErrorWithStatus:@"请填写旧密码/新密码"];
        return;
    }
}

- (void)codeButtonClick:(NSString *)fieldText completion:(void (^)(void))completion {
    NSString * phone = [[UserLocal sharedInstance] currentUserInfo].phone;
    NSString *urlStr = [NSString stringWithFormat:@"%@?phone=%@",HTTPAPIWITH(url_send_code),phone];
    [self HUDshowWithStatus:@""];
    [[PLRequestManage sharedInstance] httpRequestWithUrl:urlStr Type:RequestGet parameters:[NSMutableDictionary dictionary] completeHandle:^(id  _Nullable responseObject, NSError *error) {
        [self HUDdismiss];
        if (!error) {
            [self HUDshowSuccessWithStatus:@"验证码已发送"];
        } else {
            [self HUDshowErrorWithStatus:error.localizedDescription];
        }
        completion();
    }];
}

- (void)codeAlertFirstBtnClick:(NSString *)fieldText {
    debugLog(@"codeAlertFirstBtnClick");
    self.codeTimerView.hidden = YES;
    [self.codeTimerView showShadowView:NO];
}

- (void)codeAlertSecondBtnClick:(NSString *)fieldText view:(SLCodeInputView *)view completion:(void (^ _Nullable)(NSString *message))completion {
        //调用接口 -- 如果注册成功直接调用登录接口进行登录 -- 登录成功后 回到我的首页
    NSMutableDictionary * param = [NSMutableDictionary dictionary];
    NSString * phone = [[UserLocal sharedInstance] currentUserInfo].phone;
    NSString * token = [[UserLocal sharedInstance] currentUserInfo].token;
    [param setObject:phone forKey:@"phone"];
    [param setObject:token forKey:@"token"];
    [param setObject:fieldText forKey:@"messagecode"];
    [param setObject:self.oldPWD forKey:@"oldpwd"];
    [param setObject:self.nowPWD forKey:@"newpwd"];
    [[PLRequestManage sharedInstance] httpRequestWithUrl:HTTPAPIWITH(url_updatePwd) Type:RequestPost parameters:param completeHandle:^(id  _Nullable responseObject, NSError *error) {
        if (!error) {
//            completion(@"修改成功");
            [self HUDshowSuccessWithStatus:@"修改成功"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated:YES];
            });
            [view dismiss];
            self.codeTimerView = nil;
        } else {
            [view dismiss];
            self.codeTimerView = nil;
            [self HUDshowErrorWithStatus:error.localizedDescription];
//            completion(error.localizedDescription);
        }
    }];
}
@end
